package com.example.myapplication.utils;

import android.graphics.PointF;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class Locus {
    private String floor;
    private String start;
    private String end;

    public Locus(int floor,int start,int end){
        this.floor= Integer.toString(floor);
        this.start= Integer.toString(start);
        this.end=Integer.toString(end);
    }

    public void getLocation(Locus.LocationCallback callback) {
        if (floor!=null&&start!=null&&end!=null) {
            OkHttpUtils.get()
                    .url("http://121.36.92.128:8086/navigation")
                    .addParams("floor",floor)
                    .addParams("origin",start)
                    .addParams("destination",end)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            System.out.println(e.toString());
                            callback.onLocationError(e);
                        }

                        @Override
                        public void onResponse(String response, int id) {
                           // float[] location = new float[30];
                            List<PointF> locus=new ArrayList<>();
                            if (!response.isEmpty()) {
                                try {
                                    JSONArray jsonArray = new JSONArray(response);
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        JSONArray point = jsonArray.getJSONArray(i);
                                        float x = Float.parseFloat(Double.toString(point.getDouble(0)));
                                        float y = Float.parseFloat(Double.toString(point.getDouble(1)));
                                        PointF p=new PointF(x,y);
                                        locus.add(p);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            callback.onLocationResult(locus);
                        }
                    });
        } else {
            callback.onLocationResult(null);
        }
    }
    // 回调接口
    public interface LocationCallback {
        void onLocationResult(List<PointF> locus);
        void onLocationError(Exception e);
    }

}
